package com.aaa.forum.controller;

import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.config.AppConfig;
import com.aaa.forum.model.Message;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IMessageService;
import com.aaa.forum.services.ISubscribeService;
import com.aaa.forum.services.IUserService;
import com.aaa.forum.uitls.MD5Util;
import com.aaa.forum.uitls.StringUtil;
import com.aaa.forum.uitls.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private ISubscribeService subscribeService;

    @Resource
    private IMessageService messageService;

    /**
     * 用户注册
     * @param username          用户名
     * @param nickname          昵称
     * @param password          密码
     * @param passwordRepeat    确认密码
     * @return                  返回信息
     */
    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") String username,
                              @ApiParam("昵称") @RequestParam("nickname") String nickname,
                              @ApiParam("密码") @RequestParam("password") String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") String passwordRepeat) {
        // 1. 参数非空校验
        // 添加了 @RequestParam 注解后, 默认参数不为空 (请求必须提供参数)

//        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
//                || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
//            // 返回错误信息, 参数校验失败
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        // 2. 校验密码是否相同
        if (!password.equals(passwordRepeat)) {
            // 两次输⼊的密码不⼀致
            // 打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        // 3. 构造一个 User 对象
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        // 4. 密码加密
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        // 5. 调用 Service 层的方法
        userService.createNormalUser(user);

        // 6. 如果 Service 没有报错, 那么就返回成功
        return AppResult.success();
    }


    /**
     * 用户登录
     *
     * @param username  用户名
     * @param password  密码
     * @return          返回信息
     */
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") String username,
                           @ApiParam("密码") @RequestParam("password") String password) {
        // @RequestParam 注解, 默认了参数是必须的, 所以不需要进行参数校验
        // 1. 调用 Service 层中的登录方法
        User user = userService.login(username, password);
        // 2. 将返回的用户信息, 存储到 session 中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 3. 返回结果
        return AppResult.success();
    }

    /**
     * 根据用户id, 返回用户信息
     * @param id    用户id
     * @return      用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if (id == null) {
            // 1. 如果id为空, 返回当前登录用户的信息
            // 获取当前登录用户的关注数量
            Long subscribeCount = subscribeService.getSubscribeCount(user.getId());
            user.setSubscribeCount(subscribeCount);
            // 获取当前登录用户的粉丝数量
            Long fanCount = subscribeService.getFanCount(user.getId());
            user.setFanCount(fanCount);
            // 返回用户信息
            return AppResult.success(user);
        } else {
            // 2. 如果id不为空, 根据id从数据库中查询
            User findUser = userService.selectById(id);
            if (findUser == null || findUser.getDeleteState() == 1) {
                log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
            // 获取当前用户对查询用户的关注状态
            Byte subscribeState = subscribeService.getState(user.getId(), findUser.getId());
            findUser.setSubscribeState(subscribeState);
            // 获取被查询用户的关注数量
            Long subscribeCount = subscribeService.getSubscribeCount(findUser.getId());
            findUser.setSubscribeCount(subscribeCount);
            // 获取被查询用户的粉丝数量
            Long fanCount = subscribeService.getFanCount(findUser.getId());
            findUser.setFanCount(fanCount);
            // 返回用户信息
            return AppResult.success(findUser);
        }
    }


    /**
     * 退出登录
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        // 1. 通过http请求, 获取session对象
        HttpSession session = request.getSession(false);
        // 2. 判断session是否有效
        if (session != null) {
            // 该方法是删除session对象, 并且解绑绑定在这个对象上的任何数据
            session.invalidate();
        }
        // 3. 返回结果
        return AppResult.success();
    }

    /**
     * 修改个人信息
     *
     * @param username  用户名
     * @param nickname  昵称
     * @param gender    性别
     * @param email     邮箱
     * @param phoneNum  手机号码
     * @param remark    个人简介
     * @return  AppResult
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("手机号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 1. 参数校验, 参数不能全部为空
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed("请输入要修改的内容!");
        }

        // 2. 获取当前登录的用户对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装要更新的用户信息
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        // 4. 调用service
        userService.modifyInfo(updateUser);
        // 5. 查询更新后的用户信息
        user = userService.selectById(user.getId());
        // 6. 更新session信息
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回更新后的用户信息
        return  AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("旧密码") @RequestParam("oldPassword") String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") String newPassword,
                                    @ApiParam("确认密码") @RequestParam("repeatPassword") String repeatPassword) {
        // 校验新密码与确认密码
        if (!newPassword.equals(repeatPassword)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 销毁 session（因为修改成功后，需要重新登录）
        session.invalidate();
        // 返回结果
        return AppResult.success(ResultCode.SUCCESS);
    }

    @ApiOperation("修改头像")
    @PostMapping("/modifyAvatar")
    public AppResult modifyAvatar(HttpServletRequest request,
                                  @ApiParam("头像文件") @RequestPart("avatar") MultipartFile file) throws IOException {
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 获取文件后缀名
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 校验文件格式
        if (!".jpg".equals(fileName) && !".jpeg".equals(fileName) && !".png".equals(fileName)) {
            return AppResult.failed("图片格式错误！");
        }
        // 设置具体路径（路径+文件名+后缀名）
        String filePath = AppConfig.IMAGE_PATH + "/" + UUIDUtil.UUID_32() + "-" + user.getId() + fileName;
        // 将图片存储到指定位置
        file.transferTo(new File(filePath));
        // 去掉具体的路径（AppConfig.IMAGE_PATH）
        filePath = filePath.substring(filePath.indexOf("/images"));

        // 调用service，写入数据库
        userService.modifyAvatar(user.getId(), filePath);

        // 更新session
        user.setAvatarUrl(filePath);
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success(filePath);
    }

    @ApiOperation("通过昵称获取用户列表")
    @GetMapping("/getListByNickname")
    public AppResult<List<User>> getListByNickname(@ApiParam("用户昵称") @RequestParam("nickname") String nickname) {
        if (StringUtil.isEmpty(nickname)) {
            return AppResult.failed("请输入要查询的内容");
        }
        return AppResult.success(userService.selectByNickname(nickname));
    }

    @ApiOperation("禁言用户")
    @PostMapping("/ban")
    public AppResult banByUserId(HttpServletRequest request,
                                 @ApiParam("用户id") @RequestParam("userId") Long userId) {
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验权限
        if (user.getIsAdmin() != 1) {
            // 只有管理员可以操作
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        userService.modifyState(userId, (byte) 1);
        // 发送系统消息
        Message message = new Message();
        message.setPostUserId(0L);
        message.setReceiveUserId(userId);
        message.setContent("您已被禁言，有问题请联系管理员！");
        messageService.create(message);
        return AppResult.success();
    }

    @ApiOperation("解除禁言")
    @PostMapping("/unban")
    public AppResult unbanByUserId(HttpServletRequest request,
                                 @ApiParam("用户id") @RequestParam("userId") Long userId) {
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验权限
        if (user.getIsAdmin() != 1) {
            // 只有管理员可以操作
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        userService.modifyState(userId, (byte) 0);
        // 发送系统消息
        Message message = new Message();
        message.setPostUserId(0L);
        message.setReceiveUserId(userId);
        message.setContent("您已被解除禁言！");
        messageService.create(message);
        return AppResult.success();
    }

    @ApiOperation("获取被禁言的用户列表")
    @PostMapping("/getBanList")
    public AppResult getBanList(HttpServletRequest request) {
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验权限
        if (user.getIsAdmin() != 1) {
            // 只有管理员可以操作
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        return AppResult.success(userService.selectByState((byte) 1));
    }


    @ApiOperation("上传图片")
    @PostMapping("/uploadImage")
    public AppResult<List<String>> uploadImage(HttpServletRequest request,
                                  @ApiParam("图片文件") @RequestPart("image") List<MultipartFile> files) throws IOException {
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 校验用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        List<String> result = new ArrayList<>();

        for (MultipartFile multipartFile : files) {
            // 获取文件后缀名
            String fileName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            // 校验文件格式
            if (!".jpg".equals(fileName) && !".jpeg".equals(fileName) && !".png".equals(fileName)) {
                return AppResult.failed("图片格式错误！");
            }
            // 设置具体路径（路径+文件名+后缀名）
            String filePath = AppConfig.IMAGE_PATH + "/" + UUIDUtil.UUID_32() + "-" + user.getId() + fileName;
            // 将图片存储到指定位置
            multipartFile.transferTo(new File(filePath));
            // 去掉具体的路径（AppConfig.IMAGE_PATH）
            filePath = filePath.substring(filePath.indexOf("/images"));

            result.add(filePath);
        }

        // 返回结果
        return AppResult.success(result);
    }
}
